<template>
  <div class="tag-view">
    <!-- 标签头部 -->
    <el-card class="tag-header">
      <div class="tag-info">
        <h1>
          <el-icon><Collection /></el-icon>
          标签：{{ currentTag }}
        </h1>
        <p class="count">共 {{ total }} 篇文章</p>
      </div>
    </el-card>

    <!-- 标签云 -->
    <el-card class="tag-cloud">
      <template #header>
        <div class="header">
          <span>所有标签</span>
        </div>
      </template>
      <div class="tags">
        <el-tag
          v-for="tag in tags"
          :key="tag.name"
          :type="getTagType(tag.name)"
          :effect="tag.name === currentTag ? 'dark' : 'light'"
          class="tag-item"
          @click="handleTagClick(tag.name)"
        >
          {{ tag.name }} ({{ tag.count }})
        </el-tag>
      </div>
    </el-card>

    <!-- 博客列表 -->
    <el-card v-loading="loading" class="blog-list-card">
      <blog-list
        :blogs="blogs"
        :loading="loading"
      />
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Collection } from '@element-plus/icons-vue'
import { useBlogStore } from '@/stores/blog'
import BlogList from '@/components/blog/BlogList.vue'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

// 状态
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const currentTag = computed(() => route.params.tag as string || '')

// 标签数据
const tags = ref<Array<{ name: string; count: number }>>([])

// 计算属性
const blogs = computed(() => blogStore.blogs)

// 标签类型
const tagTypes = ['', 'success', 'warning', 'danger', 'info']

// 方法
const getTagType = (tagName: string) => {
  // 根据标签名生成固定的类型，使同一个标签始终显示相同的颜色
  const index = tagName.length % tagTypes.length
  return tagTypes[index]
}

const fetchBlogs = async () => {
  if (!currentTag.value) return
  
  loading.value = true
  try {
    await blogStore.fetchBlogs({
      page: currentPage.value,
      pageSize: pageSize.value,
      tag: currentTag.value
    })
    total.value = blogStore.total
  } catch (error) {
    console.error('Failed to fetch blogs:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTags = async () => {
  try {
    // TODO: 实现获取标签统计的逻辑
    // const res = await blogStore.fetchTags()
    // tags.value = res
    
    // 临时数据
    tags.value = [
      { name: 'Vue', count: 10 },
      { name: 'React', count: 8 },
      { name: 'TypeScript', count: 15 },
      { name: 'JavaScript', count: 20 },
      { name: 'Node.js', count: 12 },
      { name: 'Python', count: 5 },
      { name: '前端', count: 30 },
      { name: '后端', count: 18 },
      { name: '数据库', count: 7 },
      { name: '算法', count: 9 }
    ]
  } catch (error) {
    console.error('Failed to fetch tags:', error)
    ElMessage.error('获取标签列表失败')
  }
}

const handleTagClick = (tag: string) => {
  router.push({
    path: `/tag/${tag}`,
    query: { page: '1' }
  })
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  updateRoute()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  updateRoute()
}

const updateRoute = () => {
  router.push({
    path: route.path,
    query: {
      page: currentPage.value.toString(),
      size: pageSize.value.toString()
    }
  })
}

// 监听路由变化
watch(
  () => route.params.tag,
  () => {
    currentPage.value = 1
    fetchBlogs()
  }
)

watch(
  () => route.query,
  (query) => {
    currentPage.value = Number(query.page) || 1
    pageSize.value = Number(query.size) || 10
    fetchBlogs()
  },
  { immediate: true }
)

// 生命周期钩子
onMounted(() => {
  fetchTags()
})
</script>

<style lang="scss" scoped>
.tag-view {
  .tag-header {
    margin-bottom: 20px;
    
    .tag-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      h1 {
        margin: 0;
        font-size: 24px;
        display: flex;
        align-items: center;
        gap: 10px;
        
        .el-icon {
          font-size: 24px;
          color: $primary-color;
        }
      }
      
      .count {
        color: $text-secondary;
        margin: 0;
      }
    }
  }
  
  .tag-cloud {
    margin-bottom: 20px;
    
    .header {
      font-size: 16px;
      font-weight: bold;
    }
    
    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      padding: 10px 0;
      
      .tag-item {
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }
  
  .blog-list-card {
    min-height: 400px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

// 响应式布局
@media (max-width: $breakpoint-sm) {
  .tag-view {
    .tag-header {
      .tag-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }
    }
    
    .tag-cloud {
      .tags {
        gap: 8px;
        
        .tag-item {
          margin: 0;
        }
      }
    }
  }
}
</style> 